/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.servlet;

import cn.webrx.db.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>Project: jdbc202202 - SaveServlet
 * <p>Powered by webrx On 2022-08-23 10:23:38
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */

@WebServlet("/save") @MultipartConfig
public class SaveServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        String username = req.getParameter("username");
        String birthday = req.getParameter("birthday");
        String ip = req.getRemoteAddr();
        String info = req.getParameter("info");

        //处理接收文件信息
        Part file = req.getPart("photo");
        String fn = file.getSubmittedFileName();
        fn = UUID.randomUUID().toString() + fn.substring(fn.lastIndexOf("."));
        String path  = req.getServletContext().getRealPath("upload/user/");
        File t = new File(path);
        if(!t.exists()){
            t.mkdirs();
        }




        //写入数据库t_student表
        DbUtil du = new DbUtil();
        String sql = "insert into t_student(account,password,name,birthday,info,sip,photo) value(?,?,?,?,?,?,?)";
        int a = du.executeUpdate(sql,account,password,username,birthday,info,ip,"upload/user/"+fn.toLowerCase());

        String msg = "会员注册成功";
        if(a<1){
            msg = "会员注册失败";
        }else{
            file.write(path + "/" + fn.toLowerCase());
        }
        req.setAttribute("name",username);
        req.setAttribute("msg",msg);
        req.getRequestDispatcher("/msg.jsp").forward(req,resp);
    }
}
